package com.rop.znyx.search.receiver;

import cn.hutool.core.util.ObjUtil;
import com.rabbitmq.client.Channel;
import com.rop.znyx.common.constant.MqConst;
import com.rop.znyx.search.service.SkuService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/7/3
 * Time: 16:02
 * Description: 接收MQ消息
 */

@Component
@RequiredArgsConstructor
public class SkuReceiver {

    private final SkuService skuService;

    /**
     * 商品上架
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void skuUpper(Long skuId, Message message, Channel channel) throws IOException {
        if (ObjUtil.isNotNull(skuId)) {
            skuService.upperSku(skuId);
        }

        // 第一个参数：表示收到的消息的标号
        // 第二个参数：如果为true表示可以签收多个消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 商品下架
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void skuLower(Long skuId, Message message, Channel channel) throws IOException {
        if (ObjUtil.isNotNull(skuId)) {
            skuService.lowerSku(skuId);
        }

        // 第一个参数：表示收到的消息的标号
        // 第二个参数：如果为true表示可以签收多个消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
